/*************************************************************************
    > File Name: 1.pthread_tcp_server.c
    > Author: Ykk
    > Mail: 3393579535@qq.com 
    > Created Time: 2023年05月20日 星期六 15时05分06秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include"network_utils.h"

typedef struct cinfo
{
	int cfd;
	struct sockaddr_in addr;
}CINFO;
void* client_fun(void *arg);
int main(int argc,char *argv[])
{
	if(argc < 2)
	{
		printf("argc < 2???	\n");
		return 0;
	}
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
	short port = atoi(argv[1]);
	int lis_fd = tcp4bind(port,"192.168.152.129");
	Listen(lis_fd,128);
	struct sockaddr_in cli_addr;
	socklen_t len = sizeof(cli_addr);
	CINFO *info;
	while(1)
	{
		int c_fd = Accept(lis_fd,(struct sockaddr *)&cli_addr,&len);
		pthread_t pthid;
		info = malloc(sizeof(CINFO));
		info->cfd = c_fd;
		info->addr = cli_addr;
		pthread_create(&pthid,&attr,client_fun,info);
	}
	return 0;
}
void* client_fun(void *arg)
{
	CINFO *info = (CINFO *)arg;
	char ip[16] = "";
	printf("new client ip = %s\nport%d\n", 
			inet_ntop(AF_INET,&(info->addr.sin_addr.s_addr),ip,16),
			ntohs(info->addr.sin_port));
	while(1)
	{
		char buf[1024] = "";
		int count = 0;
		count = read(info->cfd,buf,sizeof(buf));
		if(count < 0){
			perror("read");
		}else if(count == 0){
			printf("client%s port%d close...\n",
			inet_ntop(AF_INET,&(info->addr.sin_addr.s_addr),ip,16),
			ntohs(info->addr.sin_port));	
			break;
		}else{
			printf("%s\n",buf);
			write(info->cfd,buf,count);
		}
	}
	close(info->cfd);
	free(info);
}
